package com.ygqh.baby.controller.os;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.mp.api.CustomApi;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.mp.model.KfAccount;
import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.tuple.Image;
import com.foxinmy.weixin4j.tuple.NotifyTuple;
import com.foxinmy.weixin4j.tuple.Text;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.ygqh.baby.ao.ImgMedia;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.ReceiveXml;
import com.ygqh.baby.ao.SystemInfo;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.controller.mobile.BaseController;
import com.ygqh.baby.handler.GiftDrawHandler;
import com.ygqh.baby.model.WxJsapiSignature;
import com.ygqh.baby.observer.ChannelScanModel;
import com.ygqh.baby.observer.Observable.ChannelScanObservable;
import com.ygqh.baby.po.YgChannel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserOpen;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.wechat.model.Action.ActionType;
import com.ygqh.baby.service.wechat.model.UserActionReport.Aggregation;
import com.ygqh.baby.service.wechat.model.UserActionReport.TimeGranularity;
import com.ygqh.baby.service.wechat.model.UserActionSet.Type;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.ThreadPool;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

@Controller
@RequestMapping(value = "/os/wx")
public class WenxinController extends BaseController {
    @Autowired
    protected SystemInfo systemInfo;
    @Autowired
    protected ThreadPool threadPool;

    @Value("${weixin.first.scan}")
    protected String firstScan;
    @Value("${weixin.second.scan}")
    protected String secondScan;
    @Value("${weixin.default.msg}")
    protected String defaultmsg;
    @Value("${kefu.keyword}")
    protected String keyWord;
    @Value("${kefu.mediaId}")
    protected String mediaId;
    @Value("${default.head.url}")
    protected String defaultHeadImage;
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private YgChannelService ygChannelService;
    @Autowired
    private YgUserOpenService ygUserOpenService;
    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private YgWeixinMenuDayService ygWeixinMenuDayService;
    @Autowired
    private ChannelScanObservable channelScanObservable;
    @Autowired
    private WxMpUserActionService wxMpUserActionService;
    @Autowired
    private YgVoteHelpService ygVoteHelpService;

    @Autowired
    private RedisDao redisDao;
    private String jdUrl = "";
    private String defaultMessage = "<a href='http://m.yiigoo.com'>1.寻觅好物，进入壹果商城</a>\n" + "<a href='http://m.yiigoo.com/return/returnList.html'>2.申请退换货</a>\n"
            + jdUrl + " 获取更多帮助，请微信回复\n" + " 【1】查看退换货规则\n" + " 【2】加入壹果粉丝福利群 \n" + " 【3】查看壹果天猫旗舰店" + "\n 每日新品上架，微信公众号推送福利文章，淘宝壹果店铺视频直播，欢迎关注~~";
    private static Map<String, String> messageList = new HashMap<String, String>();
    private static List<String> eventList = new ArrayList<String>();
    private final static String KSD_KEY = "KSD-";

    static {
        messageList.put("1", "退换货规则和流程<a href='http://m.yiigoo.com/return/wxrule.html'>戳这里查看</a>");
        messageList.put("3", "天猫旗舰店：搜索【壹果】\n淘宝店：搜索【壹果】\n京东旗舰店,<a href='http://mall.jd.com/qr/v.html?type=js&Id=597546'>戳这里进入</a>");

        eventList.add("TEMPLATESENDJOBFINISH");
        eventList.add("LOCATION");
        eventList.add("kf_switch_session");

    }

    //    @RequestMapping(value = "/wxGateway")
//    @ResponseBody
//    public void wxGateway(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String autoMessage = "";
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        ServletInputStream inputStream = request.getInputStream();
//        PrintWriter outStream = response.getWriter();
//        String signature = request.getParameter("signature");
//        String timestamp = request.getParameter("timestamp");
//        String nonce = request.getParameter("nonce");
//        String echostr = request.getParameter("echostr");
//        outStream.print(echostr);
//    }
    @RequestMapping(value = "/wxGateway")
    @ResponseBody
    public void wxGateway(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String autoMessage = "";
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ServletInputStream inputStream = request.getInputStream();
        PrintWriter outStream = response.getWriter();
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        // 加密模式
        String encrypt_type = request.getParameter("encrypt_type");
        String msg_signature = request.getParameter("msg_signature");
        WXBizMsgCrypt wxBizMsgCrypt = null;
        // 加密方式
        boolean isAes = "aes".equals(encrypt_type);

        if (isAes) {
            try {
                wxBizMsgCrypt = new WXBizMsgCrypt(systemInfo.getWeiXinCustomToken(), systemInfo.getWeiXinEncodingAesKey(), systemInfo.getWeiXinAppId());
            } catch (AesException e) {
                e.printStackTrace();
            }
        }
        String xmlData = IOUtils.toString(inputStream, "utf-8");
        ReceiveXml receiveXml = XmlStream.fromXML(xmlData, ReceiveXml.class);

        // 获取openid
        String openId = receiveXml.getFromUserName();
        // 获取场景id
        String seoid = "";
        String resultxml = "";
        String msgType = receiveXml.getMsgType();
        String content = "";
        switch (msgType) {
            case "event":
                String eventKey = receiveXml.getEventKey();
                if (StringUtils.isNotBlank(eventKey)) {
                    seoid = receiveXml.getEventKey().substring(eventKey.lastIndexOf('_') + 1);
                }

                content = initContent(seoid);

                if (receiveXml.getEvent().equals("subscribe")) {// 扫描

                    content = channelScan(openId, seoid, content, true);
                    updateSubscribeStatus(openId, true);
                    // autoMessage = "亲，终于等到你，欢迎来到壹果微信商城~~\n" + defaultMessage;

                }
                if (receiveXml.getEvent().equals("SCAN")) {// 已经关注过
                    content = channelScan(openId, seoid, content,false);
                    // autoMessage = "亲，终于等到你，欢迎来到壹果微信商城~~\n" + defaultMessage;
                }

                if (receiveXml.getEvent().equals("VIEW") || receiveXml.getEvent().toLowerCase().equals("unsubscribe")) {
                    if (receiveXml.getEvent().toLowerCase().equals("unsubscribe")) {
                        this.updateSubscribeStatus(openId, false);
                    }
                    if (receiveXml.getEvent().equals("VIEW")) {
                        ygWeixinMenuDayService.saveMenuClick(openId, receiveXml.getEventKey(), Constant.YIIGOO_PLATFORM_NO);

                    }
                    break;
                }

                resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), content);
                break;
            default:
                content = receiveXml.getContent();
                if (!msgType.equals("text")) {
                    content = "0";
                }
                if ("1".equals(content) || "2".equals(content) || "3".equals(content)) {
                    String receiveContent = messageList.get(content);
                    if (content.equals("2")) {
                        String MediaId = "";
                        MediaId = redisDao.get(ImgMedia.FansQrCode + "MediaId");
                        if (StringUtil.isNotBlank(MediaId)) {
                            sendMedia(MediaId, receiveXml);
                        }
                    } else {
                        resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), receiveContent);
                    }
                } else if ("智慧树".equals(content.trim())) {
                    content = "智慧树的亲们，等你好久了！\n <a href='http://m.yiigoo.com/promotion/tree/index.html?sourceCode=ggzhs1706'>马上点击领取你的试用机会哦~</a>";
                    resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), content);
                } else if ("试用".equals(content.trim())) {
                    content = "<a href='http://m.yiigoo.com/static/1498035463.html?sourceCode=jrttmz'>马上点击领取你的试用机会哦~</a>";
                    resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), content);
                } else if (isNewYearGift(content)) {
                    printNewYearGiftReturnMsg(content, outStream, receiveXml);
                    return;
                } else {
                    String res = redisDao.get(String.format(RedisConstant.VOTE_HELP_PREFIX, receiveXml.getFromUserName()));
                    if (StringUtils.isNotBlank(res)
                            && YgStringUtils.isChinaPhoneLegal(content.trim())) {
                        // 投票新用户输入手机号，执行场景2
                        content = ygVoteHelpService.processVoteHelpByStep2(content.trim(), receiveXml.getFromUserName(), res);
                        resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), content);
                    } else {
                        content = "亲，终于等到你，欢迎来到壹果微信商城~~\n" + defaultMessage;
                        resultxml = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), content);

                    }
                }

                break;
        }

        try {
            // 回复
            if (StringUtil.isNotBlank(autoMessage)) {
                Text text = new Text(autoMessage);
                sendNotifyMessage(receiveXml.getFromUserName(), text);
            }
            outStream.print(resultxml);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        logger.info("回复完成");

    }

    private void sendNotifyMessage(String from, NotifyTuple tuple) {
        try {
            NotifyMessage notifyMessage = new NotifyMessage(from, tuple);
            NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
            notifyAPI.sendNotify(notifyMessage);
        } catch (WeixinException e) {
            e.printStackTrace();
        }
    }

    private String initContent(String seoid) {
        YgChannel def = ygChannelService.findById(79l);
        if (!StringUtil.isEmpty(seoid)) {// 搜索关注公众号

            YgChannel channel = ygChannelService.findByCode(seoid);
            // 渠道的扫描问候语始终为主渠道的问候语。
            if (channel != null) {
                if (channel.getParentId().intValue() == 0) {
                    def = channel;
                } else {
                    def = ygChannelService.findById(channel.getParentId());
                }

            }
        }
        return def.getGreetings();
    }

    private String payOrder(String seoid, String openId) {
        if (StringUtil.isNotBlank(seoid) && seoid.startsWith(KSD_KEY)) {
            // KSD_KEY + orderId + totalPrice
            String[] str = seoid.split("-");
            if (str.length == 3) {
                boolean num = YgStringUtils.isNum(str[1]);
                if (num) {
                    return "<a href='http://m.yiigoo.com/order/payorder.html?orderId=" + str[1] + "&totalPrice=" + str[2] + "&openId=" + openId
                            + "'>亲爱的用户，您的订单号是" + str[1] + "，金额是" + str[2] + "元，请点此支付。</a>";
                }
            }

        }
        return "";
    }

    // 更新关注状态
    private void updateSubscribeStatus(String openId, Boolean isSubscribe) {
        threadPool.getExecutorService().execute(() -> ygUserService.updateSubscribeStatus(openId, isSubscribe));
    }

    private void sendMedia(String mediaId, ReceiveXml receiveXml) throws WeixinException {
        Image image = new Image(mediaId);
        NotifyMessage notifyMessage = new NotifyMessage(receiveXml.getFromUserName(), image);
        NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
        notifyAPI.sendNotify(notifyMessage);

    }

    private String channelScan(String openId, String seoid, String content, boolean subscribe) {
        content = this.specialGreeting(openId, seoid, content);


        ChannelScanModel model = new ChannelScanModel(seoid, openId, subscribe);
        channelScanObservable.channelScan(model);
        if (StringUtils.isNotBlank(model.getContent())) {
            content = model.getContent();
        }
        this.saveOpenUser(openId, seoid);

        return content;
    }

    private String specialGreeting(String openId, String seoid, String content) {
        if ("kanjia170830".equals(seoid)) {
            content = this.kanjiaGreeting(openId, seoid, content);
        } else if ("ygwlbzd".equals(seoid)) {
            content = this.christmasGreeting(openId, seoid, content);
        }
        return content;

    }

    private String kanjiaGreeting(String openId, String seoid, String content) {
        YgUser user = ygUserService.findByOpenId(openId);
        if (user == null) {
            content = "<a href='http://m.yiigoo.com/coupon/leadquan.html?sourceCode='" + seoid + ">您已成功关注壹果Yiigoo，加入麻麻剁手委员会，拿20元优惠券（一个用户限领一张）。</a>";
        } else {
            content = "<a href='http://m.yiigoo.com/user/coupon.html'>嗨！我们又见面了，麻麻剁手委员会给老会员回馈20元优惠券（一个用户限领一张）。</a>";
            ygCouponService.receiveCoupon(202L, user);
        }
        return content;
    }

    private String christmasGreeting(String openId, String seoid, String content) {
        YgUser user = ygUserService.findByOpenId(openId);
        if (user == null) {
            // 新用户
            content = "<a href='http://m.yiigoo.com/static/1511372944.html?v=21321'>终于等到你，还好我没放弃，初次见面，一生一次的新人体验价诚心奉上，点击19元包邮立享优惠</a>";
        } else {
            // 老用户
            content = "<a href ='http://m.yiigoo.com/promotion/20171130/index.html?v=21321'>亲爱的老朋友， 圣诞节快乐！现金红包等你来转！点我赢取老用户“金”喜</a>";
        }

        return content;

    }

    private void saveOpenUser(String openId, String seoid) {
        if (StringUtils.isNotBlank(seoid)) {

            threadPool.getExecutorService().execute(() -> {
                String source = seoid;
                if (source.startsWith("DrawPrize-")) {
                    source = seoid.split("-")[2];
                }
                YgUserOpen ygUser = ygUserOpenService.findByScan(openId, source);
                if (ygUser == null) {
                    User wxUser = null;
                    try {
                        wxUser = wxMpAuthorityService.getUserInfo(openId);
                    } catch (WeixinException e) {
                        e.printStackTrace();
                    }
                    YgUserOpen userOpen = new YgUserOpen();
                    userOpen.setUserName(openId);
                    userOpen.setOpenId(openId);
                    userOpen.setNickName(wxUser.getNickName());
                    String headUrl = wxUser.getHeadimgurl();
                    if (wxUser.getHeadimgurl().equals("/0")) {
                        headUrl = defaultHeadImage;
                    }
                    userOpen.setHeadImageUrl(headUrl);
                    userOpen.setSourceCode(openId);
                    userOpen.setFromCode(seoid);
                    userOpen.setCreateTime(new Date());
                    ygUserOpenService.save(userOpen);
                }
            });
        }
    }

    /**
     * 数据流输出
     *
     * @param outputStream
     * @param text
     * @return
     */
    private boolean outputStreamWrite(PrintWriter outputStream, String text) {
        try {
            outputStream.print(text.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private String transferCustomerService(String to, String from) {

        StringBuffer sb = new StringBuffer();
        sb.append("<xml><ToUserName><![CDATA[");
        sb.append(to);
        sb.append("]]></ToUserName><FromUserName><![CDATA[");
        sb.append(from);
        sb.append("]]></FromUserName><CreateTime>");
        sb.append(System.currentTimeMillis());
        sb.append("</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType>");
        sb.append("</xml>");
        return sb.toString();
    }

    private String formatXmlAnswer(String to, String from, String content) {

        StringBuffer sb = new StringBuffer();
        sb.append("<xml><ToUserName><![CDATA[");
        sb.append(to);
        sb.append("]]></ToUserName><FromUserName><![CDATA[");
        sb.append(from);
        sb.append("]]></FromUserName><CreateTime>");
        sb.append(System.currentTimeMillis());
        sb.append("</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[");
        sb.append(content);
        sb.append("]]></Content></xml>");
        return sb.toString();
    }

    @RequestMapping(value = "/generateJsapiSignature")
    @ResponseBody
    public JSONPObject generateJsapiSignature(HttpServletRequest request, @RequestParam(required = true) String callback, String url) throws Exception {
        String path_str = request.getRequestURL().toString();
        String param_str = request.getQueryString();
        System.out.println(path_str);
        System.out.println(param_str);
        System.out.println(url);
        WxJsapiSignature sig = wxMpAuthorityService.generateJsapiSignature(url);
        logger.info(JSON.toJSON(sig));
        return new JSONPObject(callback, sig);
    }

    @RequestMapping(value = "/getCus")
    @ResponseBody
    public JSONPObject getCus(String callback) throws Exception {
        CustomApi api = new CustomApi(wxMpAuthorityService.findTokenHolder());
        List<KfAccount> listKfAccount = api.listKfAccount(true);
        return new JSONPObject(callback, listKfAccount);
    }

    @RequestMapping(value = "/getCurrentTime")
    @ResponseBody
    public JSONPObject getCurrentTime(String callback) {
        return new JSONPObject(callback, Message.success(System.currentTimeMillis()));
    }

    @RequestMapping(value = "/findWxUser")
    @ResponseBody
    public JSONPObject findWxUser(String code, String callback) throws WeixinException {
        try {
            User user = wxMpAuthorityService.findUserInfo(code);
            return new JSONPObject(callback, Message.success(user));
        } catch (WeixinException e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 上报网页转化行为数据
     *
     * @param clickId
     * @param callback
     * @param currentUrl
     * @param actionType
     * @param totalPrice
     * @return
     * @throws WeixinException
     * @throws HttpClientException
     */
    @RequestMapping(value = "/userActions")
    @ResponseBody
    public JSONPObject userActions(String clickId, String callback, String currentUrl, ActionType actionType,
                                   BigDecimal totalPrice, Type type) {
        try {
            currentUrl = URLDecoder.decode(currentUrl, "utf-8");
            currentUrl = "http://m.yiigoo.com/" + currentUrl;
            Long userId = null;
            YgUser currentUser = SessionUtil.getCurrentUser();
            if (currentUser != null) {
                userId = currentUser.getId();
            }
            return new JSONPObject(callback, wxMpUserActionService.userActions(clickId, currentUrl, actionType, totalPrice, type, userId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONPObject(callback, Message.success(null));
    }

    /**
     * 获取用户行为数据源
     *
     * @param userActionSetId
     * @param callback
     * @return
     * @throws WeixinException
     * @throws HttpClientException
     */
    @RequestMapping(value = "/findUserActionSets")
    @ResponseBody
    public JSONPObject findUserActionSets(String userActionSetId, String callback) {
        try {
            return new JSONPObject(callback, wxMpUserActionService.findUserActionSets(userActionSetId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONPObject(callback, Message.success(null));
    }

    /**
     * 获取用户行为数据源报表
     *
     * @param userActionSetId
     * @param startDate
     * @param endDate
     * @param timeGranularity
     * @param aggregation
     * @param callback
     * @return
     * @throws WeixinException
     * @throws HttpClientException
     */
    @RequestMapping(value = "/findUserActionSetReports")
    @ResponseBody
    public JSONPObject findUserActionSetReports(String userActionSetId, Date startDate, Date endDate,
                                                TimeGranularity timeGranularity, Aggregation aggregation, String callback) {
        try {
            return new JSONPObject(callback, wxMpUserActionService.findUserActionSetReports(userActionSetId, startDate, endDate, timeGranularity, aggregation));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONPObject(callback, Message.success(null));
    }

    private final String NEW_YEAR_GIFT_JOIN_SIGNAL = "新年有礼";
    private final String NEW_YEAR_GIFT_SOURCE_CODE = "newYearGift";
    private final long LAST_JOIN_DATE = DateConvertUtils.parse("2019-01-23", DateConvertUtils.DATE_FORMAT).getTime();
    private final long START_DATE_OF_DRAW = DateConvertUtils.parse("2019-01-25", DateConvertUtils.DATE_FORMAT).getTime();
    private final long END_DATE_OF_DRAW = DateConvertUtils.parse("2019-02-25", DateConvertUtils.DATE_FORMAT).getTime();
//    private final static String MEDIA_ID = "7a0lScSe_yra3DW7EWHhDuVt9ApdHpdttvVnYXdKUEhNj64cOTRuPqScwSEKgGQy";
    private final static String MEDIA_ID = "Z57AA9fWO1XUzbReyiuHQcfR4Iune8sCRLxS8NUdRgwDkRdSUavX_Nmq1NxTAoqY";

    @Autowired
    private GiftDrawHandler giftDrawHandler;

    private boolean isNewYearGift(String content) {
        content = content != null ? content.trim() : content;
        return NEW_YEAR_GIFT_JOIN_SIGNAL.equals(content);
    }

    /**
     * 19年“朋友圈转发得大奖”活动
     */
    private void printNewYearGiftReturnMsg(String content, PrintWriter outStream, ReceiveXml receiveXml) {

        if (NEW_YEAR_GIFT_JOIN_SIGNAL.equals(content)) {
            StringBuilder sb = new StringBuilder();
            if (System.currentTimeMillis() < LAST_JOIN_DATE) {
                sb.append("第一步：长按识别二维码，生成专属海报，生成专属海报\n\n");
                sb.append("第二步：1月23号前发海报到朋友圈(不可设为分组或删除)\n\n");
                sb.append("第三步：等待开奖。2019年1月25日，在壹果公众号回复“新年有礼”查询抽奖结果。");
                Image image = new Image(MEDIA_ID);
                sendNotifyMessage(receiveXml.getFromUserName(), image);
            } else if (System.currentTimeMillis() >= LAST_JOIN_DATE && System.currentTimeMillis() < START_DATE_OF_DRAW) {
                sb.append("活动已结束，等待开奖！");

            } else if (System.currentTimeMillis() >= START_DATE_OF_DRAW && System.currentTimeMillis() < END_DATE_OF_DRAW) {
                //开奖
//                中奖返回：恭喜您抽中锦鲤！壹果宠你~请联系客服领奖
//                没中奖返回： 有点遗憾，没有中奖哦。欢迎进入壹果妈妈群，享受专属群福利、群特价！进群点这里  超链接http://m.yiigoo.com/static/1534417413.html

                Boolean winOfNewYearGift = giftDrawHandler.isWinOfNewYearGift(NEW_YEAR_GIFT_SOURCE_CODE, receiveXml.getFromUserName());
                if (winOfNewYearGift) {
                    sb.append("恭喜您抽中锦鲤！壹果宠你~请联系客服领奖。");
                } else {
                    sb.append("有点遗憾，没有中奖哦。欢迎进入壹果妈妈群，享受专属群福利、群特价！ <a href='http://m.yiigoo.com/static/1534417413.html'>进群点这里 </a>。");
                }
            } else {
                sb.append("活动已结束！");
            }
            String s = formatXmlAnswer(receiveXml.getFromUserName(), receiveXml.getToUserName(), sb.toString());
            outStream.print(s);

        }
    }
}
